package com.ruoyi.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;

@RestController
@RequestMapping("/user")
public class UserInfoController {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private PasswordEncoder passwordEncoder;


    @PostMapping("/register")
    public AjaxResult registerUser(String userName,String password){
        SysUser sysUser1 = sysUserMapper.selectUserByUserName(userName);
        if (Objects.nonNull(sysUser1)){
            return AjaxResult.error("注册失败,用户已存在。");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        sysUser.setNickName(userName);
        sysUser.setSex("男");
        sysUser.setPassword(passwordEncoder.encode(password));
        sysUserMapper.insertUser(sysUser);
        System.out.println(sysUser + "我是测试查看");
        //返回结果
        return AjaxResult.success("注册成功");
    }

    @PostMapping("/get/user")
    public AjaxResult getUser(){
        //返回结果
        return AjaxResult.success(sysUserMapper.selectUserById(SecurityUtils.getUserId()));
    }

    @PostMapping("/get/{id}")
    public AjaxResult getUserById(@PathVariable(value = "id")Long id){
        //返回结果
        return AjaxResult.success(sysUserMapper.selectUserById(id));
    }

    @PostMapping("/update/user")
    public AjaxResult updateUser(@RequestBody SysUser sysUser){
        System.out.println(sysUser + "我是修改用户的值");

        if (StringUtils.isNotBlank(sysUser.getPassword())){
            String encode = passwordEncoder.encode(sysUser.getPassword());
            System.out.println(encode);
            sysUser.setPassword(encode);
        }
        sysUserMapper.updateUser(sysUser);

        return AjaxResult.success("修改成功");
    }

}
